package com.googlemail.drewwilliams1982.SoundWitch;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
	
	private AudioManager _audioManager;
	private boolean _phoneIsSilent;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        _audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);

        setButtonClickListener();
        checkIfPhoneIsSilent();
    }
    
    private void setButtonClickListener() 
    {
    	Button toggleButton = (Button)findViewById(R.id.toggleButton);
    	toggleButton.setOnClickListener
    	(
			new View.OnClickListener() 
	    	{
		    	public void onClick(View v) 
		    	{
		    		if (_phoneIsSilent) 
		    		{
		    			// Change back to normal mode
		    			_audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
		    			_phoneIsSilent = false;
	    			}
		    		else
		    		{
		    			// Change to silent mode
		    			_audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
		    			_phoneIsSilent = true;
	    			}
		    		// Now toggle the UI again
		    		toggleUi();
		    	}
	    	}
    	);
    }
    
    private void checkIfPhoneIsSilent() 
    {
    	int ringerMode = _audioManager.getRingerMode();
    	if (ringerMode == AudioManager.RINGER_MODE_SILENT) 
    	{
    		_phoneIsSilent = true;
    	} 
    	else 
    	{
    		_phoneIsSilent = false;
    	}
	}
    
	/**
	* Toggles the UI images from silent to normal and vice versa.
	*/
	private void toggleUi() 
	{
		ImageView imageView = (ImageView) findViewById(R.id.music_icon);
		Drawable newPhoneImage;
		if (_phoneIsSilent) 
		{
			newPhoneImage = getResources().getDrawable(R.drawable.nomusic);
		}
		else 
		{
			newPhoneImage =	getResources().getDrawable(R.drawable.loudmusic);
		}
		imageView.setImageDrawable(newPhoneImage);
	}
	
	@Override
	protected void onResume() 
	{
		super.onResume();
		checkIfPhoneIsSilent();
		toggleUi();
	}
}